package ru.reinvent.perspectiva.fragments;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;

import org.joda.time.format.DateTimeFormat;

import ru.reinvent.perspectiva.R;
import ru.reinvent.perspectiva.cash.Lot;
import ru.reinvent.perspectiva.cash.PerspectivaProvider;
import ru.reinvent.perspectiva.cash.PerspectivaProvider.L;
import ru.reinvent.perspectiva.cash.PerspectivaProvider.V;
import ru.reinvent.perspectiva.cash.Vendor;

import com.actionbarsherlock.app.SherlockFragment;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.assist.FailReason;
import com.nostra13.universalimageloader.core.assist.ImageLoadingListener;

import android.content.Context;
import android.content.res.Resources;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.WebView;
import android.widget.ImageView;

public class OneLotFragment extends SherlockFragment
	{
	protected final String VENDOR_STUB = "{$vendor}";
	protected final String LOT_STUB = "{$lot}";
	protected final String GENDER_STUB = "{$gender}";
	protected final String PRICE_STUB = "{$price}";
	protected final String TYPE_STUB = "{$type}";
	protected final String HULL_STUB = "{$hull}";
	protected final String REFFERENCE_STUB = "{$refference}";
	protected final String ADDDATE_STUB = "{$adddate}";
	protected final String DESCRIPTION_STUB = "{$desc}";
	protected final String STATE_STUB = "{$state}";
	
	protected final String TYPE_LBL_STUB = "{$type_lbl}";
	protected final String HULL_LBL_STUB = "{$hull_lbl}";
	protected final String REFFERENCE_LBL_STUB = "{$refference_lbl}";
	protected final String ADDDATE_LBL_STUB = "{$adddate_lbl}";
	protected final String DESCRIPTION_LBL_STUB = "{$desc_lbl}";
	protected final String STATE_LBL_STUB = "{$state_lbl}";
	
	protected int lotId = -1; 
	protected View content;
	protected Context ctx;
	
	protected ImageLoadingListener imgViewBgChanger = new ImageLoadingListener() 
		{
		@Override
		public void onLoadingCancelled() {;}
		@Override
		public void onLoadingFailed(FailReason fr) {;}
		@Override
		public void onLoadingStarted() {;}

		@Override
		public void onLoadingComplete(Bitmap bmp) 
			{
			if (content == null) return;
			ImageView img = (ImageView) content.findViewById(R.id.one_lot_image);
			img.setBackgroundColor(bmp.getPixel(0,0));
			}
		};
 
	
	public OneLotFragment() {;}
	
	public OneLotFragment(int lotId)
		{
		this.lotId = lotId;
		}
	
	@Override
	public View onCreateView(LayoutInflater inflater,ViewGroup container,Bundle savedInstanceState) 
		{
		this.ctx = getActivity();
		if (content != null) 
			{
			if (content.getParent() != null) ((ViewGroup) content.getParent()).removeView(content);
			return content;
			}
		
		content = inflater.inflate(R.layout.one_lot_fragment, container, false);
		refresh();
		
		return content;
		}
	
	public void refresh()
		{
		if (content == null) return;
		if (lotId == -1) { hideContent(); return; }
		((ImageView) content.findViewById(R.id.one_lot_image)).setImageBitmap(null);
		showContent();

		final Uri lotUri = Uri.withAppendedPath(L.CONTENT_URI,String.valueOf(lotId));
		Cursor c = ctx.getContentResolver().query(lotUri,null,null,null,null);
		if (c.getCount() == 0) { hideContent(); return; }
		c.moveToFirst();
		final Lot lot = PerspectivaProvider.DBUsage.createLot(c);
		
		final Uri vndUri = Uri.withAppendedPath(V.CONTENT_URI,String.valueOf(lot.getVendorId()));
		c = ctx.getContentResolver().query(vndUri,null,null,null,null);
		if (c.getCount() == 0) { hideContent(); return; }
		c.moveToFirst();
		final Vendor vnd = PerspectivaProvider.DBUsage.createVendor(c);
		
		final String html = buildHtml(lot,vnd);
		if (html == null) { hideContent(); return; }

		final ImageLoader imageLoader = ImageLoader.getInstance();
		String encodedImageUrl = lot.getImageUrl().replace(" ", "%20");
		imageLoader.displayImage(encodedImageUrl,(ImageView) content.findViewById(R.id.one_lot_image),imgViewBgChanger); 
						
		WebView wv = (WebView) content.findViewById(R.id.one_lot_info);
		wv.loadData(html,"text/html; charset=utf-8","UTF-8");
		wv.reload();
		wv.setBackgroundColor(ctx.getResources().getColor(R.color.black));
		}
	
	protected String buildHtml(Lot lot, Vendor vnd)
		{
		BufferedReader in = null;
		StringBuffer sb = null;
		try
			{
			sb = new StringBuffer();
			in = new BufferedReader(new InputStreamReader(ctx.getAssets().open("one_lot_template.html")));
			String line = null;
			while ((line = in.readLine()) != null) sb.append(line);
			in.close();					
			} 
		catch (Exception e) { sb = null; }
		finally { if (in != null) try { in.close(); } catch(Exception e) {;} }
		if (sb == null) return null;
		
		Resources r = ctx.getResources();
		String s;
		try { s = new String(sb.toString().getBytes(),"UTF-8"); } 
		catch (UnsupportedEncodingException e) { return null; }
		
		s = s.replace(VENDOR_STUB,vnd.getName());
		s = s.replace(LOT_STUB,lot.getName());
		s = s.replace(GENDER_STUB,lot.getGender());
		s = s.replace(PRICE_STUB,lot.getPrice());
		s = s.replace(TYPE_STUB,lot.getType());
		s = s.replace(HULL_STUB,lot.getHull());
		s = s.replace(REFFERENCE_STUB,lot.getReference());
		s = s.replace(ADDDATE_STUB,lot.getAddDate().toString(DateTimeFormat.forPattern("dd.MM.yyyy")));
		s = s.replace(DESCRIPTION_STUB,lot.getDescription());
		s = s.replace(STATE_STUB,lot.getState());
		
		s = s.replace(TYPE_LBL_STUB,r.getText(R.string.one_lot_type_lbl));
		s = s.replace(HULL_LBL_STUB,r.getText(R.string.one_lot_hull_lbl));
		s = s.replace(REFFERENCE_LBL_STUB,r.getText(R.string.one_lot_refference_lbl));
		s = s.replace(ADDDATE_LBL_STUB,r.getText(R.string.one_lot_adddate_lbl));
		s = s.replace(DESCRIPTION_LBL_STUB,r.getText(R.string.one_lot_desc_lbl));
		s = s.replace(STATE_LBL_STUB,r.getText(R.string.one_lot_state_lbl));
		
		return s;
		}
	
	protected void showContent()
		{
		if (content == null) return;
		
		content.findViewById(R.id.one_lot_fail_text).setVisibility(View.GONE);
		content.findViewById(R.id.one_lot_image).setVisibility(View.VISIBLE);
		content.findViewById(R.id.one_lot_info).setVisibility(View.VISIBLE);
		}
	
	protected void hideContent()
		{
		if (content == null) return;
		
		content.findViewById(R.id.one_lot_fail_text).setVisibility(View.VISIBLE);
		content.findViewById(R.id.one_lot_image).setVisibility(View.GONE);
		content.findViewById(R.id.one_lot_info).setVisibility(View.GONE);
		}
	
	public int getLotId()
		{
		return lotId;
		}
	
	public void setLotId(int lotId)
		{
		this.lotId = lotId;
		}
	}
